checkCookie()

// let productList = [];
const rootEle = document.querySelector('.cart-list')
let money = 0;

//渲染表格
function loadProductList() {
    //得到字符串类型全选状态
    let checkAllState = localStorage.getItem('checkAllState') || 'false';
    let productList = JSON.parse(localStorage.getItem('productList')) || [];
    let str = `<table>
                <tr>
                    <th><input type="checkbox" class="checkbox" name="checkall" ${checkAllState=="true"?'checked':''}>全选</th>
                    <th>商品图片</th>
                    <th class="infoTh">商品信息</th>
                    <th>单价</th>
                    <th>数量</th>
                    <th width="100px">总价</th>
                    <th>操作</th>
                </tr>`
    //循环遍历商品数组，拼接商品列表成表格项tr字符串
    let newArray = productList.map(item => {
        return `<tr>
                    <td><input type="checkbox" class="checkbox" name="checksingle" ${item.state?"checked":""} data-index=${item.id}></td>
                    <td><img src="${item.url}" alt=""></td>
                    <td>${item.name}</td>
                    <td>￥${item.price}</td>
                    <td>
                    <input type="button" name="minus" value="-" data-index="${item.id}" ${item.num ==0? 'disabled':''}><input type="text" name="amount" data-index="${item.id}" value="${item.num}"><input type="button" name="plus" value="+" data-index="${item.id}">
                    </td>
                    <td class="single-price" data-price="singlePrice">￥${item.singlePrice}</td>
                    <td><a href="#" class="del" data-index="${item.id}">删除</a></td>
                </tr>`
    });
    let trStr = newArray.join('')
    str = str + trStr + '</table>'
    rootEle.innerHTML = str
}

loadProductList()


function onCart() {
    rootEle.addEventListener('click', function (e) {
        e = e || window.event //事件对象
        let target = e.target || e.srcElement //事件目标对象

        //加号按钮事件
        if (target.value == '+') {
            let productList = JSON.parse(localStorage.getItem('productList')) || [];
            //操作商品数组数据
            //1.获取当前点击商品ID
            let id = target.getAttribute('data-index')
            //2.根据id查找商品
            let product = productList.find(item => item.id == id)
            product.num++
            //2.1计算价格
            product.singlePrice = (product.num * product.price).toFixed(2)
            localStorage.setItem('productList', JSON.stringify(productList));
            //3.重新渲染商品列表
            loadProductList()
            allCheckedPrices()
        }

        //减号按钮事件
        if (target.value == '-') {
            productList = JSON.parse(localStorage.getItem('productList')) || [];
            //1.获取当前点击商品ID
            let id = target.getAttribute('data-index');
            //2.根据id查找商品
            let product = productList.find(item => item.id == id);
            product.num--
            //2.1计算价格
            product.singlePrice = (product.num * product.price).toFixed(2);
            localStorage.setItem('productList', JSON.stringify(productList));
            //3.重新渲染商品列表
            loadProductList()
            allCheckedPrices()
        }

        //删除事件
        if (target.getAttribute('class') == 'del') {
            //根据属性获得当前商品的id
            let id = target.getAttribute('data-index');
            //从持久化层获取商品列表
            let productList = JSON.parse(localStorage.getItem('productList'));
            //根据id得到商品对象在数组中的下标
            let index = productList.findIndex(item => item.id == id);
            //根据下标删除该项商品
            productList.splice(index, 1);
            //删除后重新存储到持久化层
            localStorage.setItem('productList', JSON.stringify(productList));
            localStorageCheck();
            //删除完后以及存储后重新渲染页面
            loadProductList();
            allCheckedPrices()
        }

        //全选点击
        if (target.name == "checkall") {
            //如果持久化存储没有商品数组就创建一个空的数组
            let productList = JSON.parse(localStorage.getItem('productList')) || [];
            //有商品才能点击全选
            if (productList.length != 0) {
                //全选状态
                let checkAllState = localStorage.getItem('checkAllState') || 'false';
                checkAllState = checkAllState == 'true' ? true : false;
                //点击一次就取反
                checkAllState = !checkAllState;
                //遍历商品数组，让单个商品的复选框等于全选的状态
                productList.forEach(item => item.state = checkAllState);
                //修改后重新存储
                localStorage.setItem('productList', JSON.stringify(productList));
                //重新存储全选状态
                localStorage.setItem('checkAllState', checkAllState);
                allCheckedPrices()
                //重新渲染页面
                loadProductList();
            } else {
                alert('当前没有商品');
                checkAllState = false;
                loadProductList();
            }
        }

        //单个商品复选点击
        if (target.name == "checksingle") {
            //得到商品id
            let id = target.getAttribute("data-index");
            //如果持久化存储没有商品数组就创建一个空的数组
            let productList = JSON.parse(localStorage.getItem('productList')) || [];
            //遍历找到选择的那项商品
            let product = productList.find(item => item.id == id);
            // 改变那项商品的状态
            product.state = !product.state;
            //遍历所有商品的状态，都为true返回真，改变全选状态
            checkAllState = productList.every(item => item.state == true);
            //重新存储全选状态
            localStorage.setItem('checkAllState', checkAllState);
            //修改后重新存储单个复选框的值
            localStorage.setItem('productList', JSON.stringify(productList));

            //修改后重新渲染
            loadProductList();
            allCheckedPrices();
        }
    });
}


//获取所有商品总价节点
let oSpan = document.querySelector('.total>span');
//计算所有选中的总价
function allCheckedPrices() {
    let productList = JSON.parse(localStorage.getItem('productList')) || [];
    let totalPrice = 0;
    productList.forEach(item => {
        if (item.state == true) {
            totalPrice += Number(item.singlePrice)
        }
    });
    totalPrice = totalPrice.toFixed(2);
    oSpan.innerHTML = totalPrice + '元';
    money = totalPrice;
}
//判断存储商品数组还有没有数据，没有则删除全选状态
function localStorageCheck() {
    let productList = JSON.parse(localStorage.getItem('productList'));
    if (productList.length == 0) {
        localStorage.removeItem('checkAllState');
    }
}
loadProductList()
onCart()

localStorageCheck()
allCheckedPrices()

document.onchange = function (e) {
    e = e || window.event;
    let target = e.target || e.srcElement;
    if (target.name == "amount") {
        productList = JSON.parse(localStorage.getItem('productList')) || [];
        //操作商品数组数据
        //1.获取当前点击商品ID
        let id = target.getAttribute('data-index')
        console.log('a', id, 'a')
        //2.根据id查找商品
        let product = productList.find(item => item.id === id)
        product.num = target.value;
        //2.1计算价格
        product.singlePrice = (product.num * product.price).toFixed(2)
        localStorage.setItem('productList', JSON.stringify(productList));
        //3.重新渲染商品列表
        loadProductList()
        allCheckedPrices()
    }
}

function pay() {
    let payBtn = document.querySelector('.pay');
    payBtn.addEventListener('click', function () {
        alert('您本次共消费' + money + '元');
    });
}
pay()

function checkCookie() {
    if (!getCookie('username')) {
        alert('请先登录');
        window.location.href = "../login.html";
    }
}